<template>
  <el-dialog
    :title="headTitle"
    :visible="showDialog"
    style="width:1400px"
    @close="resetForm"
  >
    <el-form ref="form" :model="formData" label-width="80px" :rules="rules">
      <el-form-item label="权限名称" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="权限标识" prop="code"
        ><el-input v-model="formData.code"></el-input>
      </el-form-item>
      <el-form-item label="权限描述" prop="description"
        ><el-input v-model="formData.description"></el-input>
      </el-form-item>

      <el-form-item label="开启" prop="enVisible">
        <el-switch
          v-model="formData.enVisible"
          active-value="1"
          inactive-value="0"
        ></el-switch>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="resetForm">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import {
  getSysPermissionApi,
  UploadSysPermissionApi,
  addSysPermissionApi
} from '../../../api/permission'
export default {
  props: ['headTitle', 'showDialog', 'userId'],
  data () {
    return {
      formData: {
        name: '',
        code: '',
        description: '',
        enVisible: '',
        type: '',
        pid: ''
      },
      rules: {
        name: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
        code: [{ required: true, message: '请输入权限标识', trigger: 'blur' }]
      }
    }
  },
  methods: {
    submitForm () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            if (this.headTitle === '编辑权限') {
              await UploadSysPermissionApi({
                ...this.formData,
                type: 2,
                pid: this.userId
              })
            } else {
              await addSysPermissionApi({
                ...this.formData,
                type: 2,
                pid: this.userId
              })
            }
            this.$message.success('操作成功')
            this.formData = {
              name: '',
              code: '',
              description: '',
              enVisible: '',
              type: '',
              pid: ''
            }
          } catch (err) {
            this.$message.error(err.message)
          }
          this.$emit('upload')
          this.$emit('update:showDialog', false)
        } else {
          this.$message.error('请输入必须项')
        }
      })
    },
    async getSysPermission (id) {
      const res = await getSysPermissionApi(id)
      console.log(res)
      this.formData = res
    },
    // 关闭dialog弹窗
    resetForm () {
      this.$emit('update:showDialog', false)
      this.formData = {
        name: '',
        code: '',
        description: '',
        enVisible: '',
        type: '',
        pid: ''
      }
    }
  }
}
</script>

<style></style>
